<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="referrer" content="no-referrer" />
    <title>视频列表页面</title>
    <link rel="stylesheet" href="/css/video.css" />
    <script src="/js/jquery-1.9.1.min.js"></script>
    <style>
      .video-list-container {
        display: flex;
        flex-direction: column;
        gap: 20px;
        padding: 20px;
      }
      .video-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        overflow: hidden;
        background: #fff;
      }
      .video-item {
        display: flex;
        flex-direction: row;
        align-items: flex-start;
      }
      .video-item video {
        width: 150px;
        height: 100px;
        object-fit: cover;
        flex-shrink: 0;
      }
      .video-info {
        padding: 15px;
        flex-grow: 1;
      }
      .video-info h3 {
        margin: 0 0 10px 0;
        font-size: 16px;
      }
      .video-info p {
        margin: 0;
        color: #666;
        font-size: 12px;
      }
      .action-buttons {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 15px;
        background: #fff;
        box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: center;
        gap: 15px;
      }
      .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
      }
      .btn-primary {
        background: #007bff;
        color: white;
      }
      .btn-secondary {
        background: #6c757d;
        color: white;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="content-box">
        <div class="video-list-container">
          <!-- 视频列表将在这里动态生成 -->
        </div>
        <div class="action-buttons">
          <button class="btn btn-primary" id="downloadAll">下载全部视频</button>
          <button class="btn btn-secondary" id="copyAllText">
            复制全部文案
          </button>
        </div>
      </div>
    </div>
  </body>
</html>
<script>
  const resources = JSON.parse(sessionStorage.getItem("resources"));
  console.log("解析资源", resources);

  // 创建视频列表
  function createVideoList() {
    const container = document.querySelector(".video-list-container");
    if (!resources || resources.length === 0) {
      container.innerHTML = "<p>暂无视频资源</p>";
      return;
    }

    // 限制最多显示20条视频
    const maxVideos = 20;
    let videoCount = 0;

    for (let i = 0; i < resources.length && videoCount < maxVideos; i++) {
      const { data } = resources[i];
      const videoItems = data.res.filter((item) => item.resType == "3");
      if (videoItems.length > 0) {
        const videoCard = document.createElement("div");
        videoCard.className = "video-card";
        videoCard.innerHTML = `
          <div class="video-item">
            <video src="${videoItems[0].resUrl}" controls></video>
            <div class="video-info">
              <h3>${data.title || data.desc || `视频 ${videoCount + 1}`}</h3>
            </div>
          </div>
        `;
        container.appendChild(videoCard);
        videoCount++;
      }
    }

    // 如果视频数量超过限制，显示提示信息
    if (resources.length > maxVideos) {
      const warningMessage = document.createElement("p");
      warningMessage.style.color = "#ff6b6b";
      warningMessage.style.textAlign = "center";
      warningMessage.style.marginTop = "10px";
      warningMessage.textContent = `注意：仅显示前 ${maxVideos} 条视频`;
      container.appendChild(warningMessage);
    }
  }

  // 下载单个视频
  async function downloadVideo(videoUrl, fileName) {
    try {
      videoUrl = videoUrl.replace("http://", "https://");
      const response = await fetch(videoUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      // 使用当前时间作为文件名
      const now = new Date();
      const timeStr = now
        .toLocaleString("zh-CN", {
          year: "numeric",
          month: "2-digit",
          day: "2-digit",
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          hour12: false,
        })
        .replace(/[/\s:]/g, "-");
      a.download = `${timeStr}.mp4`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (err) {
      console.error("下载视频失败:", err);
      throw err;
    }
  }

  // 下载所有视频
  document.getElementById("downloadAll").addEventListener("click", async () => {
    try {
      const videos = document.querySelectorAll("video");
      for (let i = 0; i < videos.length; i++) {
        const video = videos[i];
        const timestamp = new Date().getTime();
        const fileName = `${timestamp}_${i + 1}.mp4`;
        await downloadVideo(video.src, fileName);
        // 添加延迟以避免浏览器限制
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
      alert("所有视频下载完成");
    } catch (err) {
      console.error("批量下载视频失败:", err);
      alert("下载过程中出现错误，请重试");
    }
  });

  // 复制所有文案
  document.getElementById("copyAllText").addEventListener("click", async () => {
    try {
      const allText = Array.from(
        document.querySelectorAll(".video-info h3, .video-info p")
      )
        .map((el) => el.textContent)
        .filter((text) => text.trim())
        .join("\n\n");

      await navigator.clipboard.writeText(allText);
      alert("所有文案已复制到剪贴板");
    } catch (err) {
      console.error("复制文案失败:", err);
      alert("复制文案失败，请手动复制");
    }
  });

  // 初始化页面
  createVideoList();
</script>
